using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class DonutMesh : MonoBehaviour{
	
	public float radiusInner = 0.5f;
	public float alphaInner = 0.8f;
	public float alphaOuter = 1f;
	public int detail = 180;
	
	private Color[] _colors;
	private Vector3[] _vertices;
	private Mesh _mesh;
	
	void Awake(){
		// at some point need to calculate this based on viewport size!
		float radiusOuter = 1.8f;
		
		_vertices = new Vector3[detail*2];
		_colors = new Color[detail*2];
		Vector2[] uvs = new Vector2[detail*2];
		int[] triangles = new int[detail*6];
		
		float a = 0;
		float astep = (360f/(float)detail)*Mathf.Deg2Rad;
		float atarget = 360f*Mathf.Deg2Rad;
		int vi = 0;
		
		while(a<atarget){
			_vertices[vi] = new Vector3(Mathf.Cos(a)*radiusInner,Mathf.Sin(a)*radiusInner,0);
			_vertices[vi+1] = new Vector3(Mathf.Cos(a)*radiusOuter,Mathf.Sin(a)*radiusOuter,0);
						
			uvs[vi] = new Vector2();
			uvs[vi+1] = new Vector2();
			
			_colors[vi] = new Color(0,0,0,alphaInner);
			_colors[vi+1] = new Color(0,0,0,alphaOuter);
			
			vi += 2;
			a += astep;
		}
		
		vi=0;
		int vi2 = 0;
		int ti = 0;
		int l = _vertices.Length;
		for(; vi<l; vi+=2){
			vi2 = vi==_vertices.Length-2 ? 0 : vi+2;
			
			triangles[ti] = vi+1;
			triangles[ti+1] = vi;
			triangles[ti+2] = vi2+1;
			
			triangles[ti+3] = vi2+1;
			triangles[ti+4] = vi;
			triangles[ti+5] = vi2;
			
			ti += 6;
		}
		
		
		_mesh = new Mesh();	
		_mesh.vertices = _vertices;
		_mesh.triangles = triangles;
		_mesh.uv = uvs;
		_mesh.colors = _colors;
		_mesh.RecalculateNormals();
		
		GetComponent<MeshFilter>().mesh = _mesh;
	}
	
	public void updateInner(){
		int vi=0;
		float a = 0;
		float astep = (360f/(float)detail)*Mathf.Deg2Rad;
		float atarget = 360f*Mathf.Deg2Rad;
		while(a<atarget){
			_vertices[vi] = new Vector3(Mathf.Cos(a)*radiusInner,Mathf.Sin(a)*radiusInner,0);
			_colors[vi] = new Color(0,0,0,alphaInner);
			_colors[vi+1] = new Color(0,0,0,alphaOuter);
			
			vi += 2;
			a += astep;
		}
				
		_mesh.vertices = _vertices;
		_mesh.colors = _colors;
	}	
}

